<?php

namespace app\admin\controller\kuerp;

use app\admin\model\kuerp\ExpenseInfo;
use app\admin\model\kuerp\Prefix;
use addons\kuerp\model\Message;
use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\Flows;
use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 报销管理
 *
 * @icon fa fa-circle-o
 */
class Expense extends Backend
{

    /**
     * Expense模型对象
     * @var \app\admin\model\kuerp\Expense
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuerp\Expense;

        $this->assignconfig('admin_id',$this->auth->id);
        $this->assignconfig('pay_auth',$this->auth->check('kuerp/expense/changePayStatus'));
        $this->assignconfig('edit_auth',$this->auth->check('kuerp/expense/edit'));
        $this->assignconfig('del_auth',$this->auth->check('kuerp/expense/del'));
        $this->assignconfig('backApply_auth',$this->auth->check('kuerp/expense/backApply'));
        $this->assignconfig('approvedEdit',$this->auth->check('kuerp/expense/approvedEdit'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $adminids = $this->auth->adminids;
        //系统设置特定审核人员
        $config_site_examine_admins = config('site.examine_admins');
        if (!empty($config_site_examine_admins[$this->auth->id])) {
            $config_examine_admins = explode(',', $config_site_examine_admins[$this->auth->id]);
            $adminids = array_merge($adminids, $config_examine_admins);
        }

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $wheres = [];
            if (!$this->auth->isSuperAdmin()) {
                $wheres['admin_id'] = ['in', $adminids];
            }
            $wheres['id'] = ['exp', Db::raw(' > 0 and ((check_status = 0 and admin_id = '.$this->auth->id.') or check_status > 0)')];
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if (isset($filter['income_month'])) {
                // 自定义处理
                $income_month = $filter['income_month'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['income_month'],$op['income_month']);
                $wheres['income_month'] = strtotime($income_month);
            }
            $this->request->get(['filter'=>json_encode($filter,true)]);
            $this->request->get(['op'=>json_encode($op,true)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->where($wheres)
                    ->order($sort, $order)
                    ->paginate($limit);
            // echo $this->model->getLastSql();
            foreach ($list as $row) {
                $row->visible(['id','expense_code','cost','income_month','start_time','subject_matter','end_time','admin_id','did','pay_status','remark','createtime','updatetime','check_status', 'admin', 'check_last_uid', 'last_checkadmin']);
                
            }
            if ($list->items()) {
                $admins = array_column($list->items(), 'admin_id');
                $check_last_uids = array_column($list->items(), 'check_last_uid');
                $adminids = array_values(array_unique(array_merge($admins, $check_last_uids)));
                $adminlist = Db::name('admin')->where('id', 'in', $adminids)->column('nickname,avatar', 'id');
                foreach ($list as $key => $value) {
                    $list[$key]['admin'] = $adminlist[$value['admin_id']] ?? [];
                    $list[$key]['last_checkadmin'] = $adminlist[$value['check_last_uid']] ?? [];
                }
            }
            $staticsinfo = $this->model->where($where)->where($wheres)->field('IFNULL(sum(cost), 0) as total_cost, IFNULL(sum(if(check_status = 2, cost, 0)), 0) as pass_cost, IFNULL(sum(if(check_status = 1, cost, 0)), 0) as passing_cost, IFNULL(sum(if(check_status = 3, cost, 0)), 0) as nopass_cost,IFNULL(sum(if(check_status = 2 and pay_status = 0, cost, 0)), 0) as nopay_cost,IFNULL(sum(if(pay_status = 1, cost, 0)), 0) as pay_cost')->find()->toArray();//->sum('cost');
            $result = array("total" => $list->total(), "rows" => $list->items(),"extend" => $staticsinfo);

            return json($result);
        }
        //获取报销人列表 搜索
        
        $adminlist = Admin::where('id', 'in', $adminids)->column('nickname','id');
        $this->assignconfig('adminlist', $adminlist);
        //审核人
        $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
        $examine_adminids = [];
        if (!empty($flows)) {
            $flows['flow_items'] = json_decode($flows['flow_items'], true);
            foreach ($flows['flow_items'] as $key => $value) {
                $examine_adminids = array_merge($examine_adminids, explode(',',$value['admin_id']));
            }
        }
        $examine_admins = Admin::where('id', 'in', $examine_adminids)->column('nickname','id');
        $this->assignconfig('examine_admins', $examine_admins);
        return $this->view->fetch();
    }

    public function add()
    {
        $infoModel = new ExpenseInfo();
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try {
                $result = $this->model->addExpense($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            return $this->success('添加成功');
        }
        $code = (new Prefix())->getCodes('',28);
        $this->view->assign('code', $code);
        
        $table = $infoModel->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME as name,COLUMN_COMMENT as comment,DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        //排除字段
        $excludeFields = ['id','expense_id','admin_id','createtime','updatetime'];
        foreach ($list as $k => $v) {
            if (in_array($v['name'], $excludeFields)) {
                continue;
            }
            $fieldArr[] = $v;
        }
        $this->view->assign('fields', $fieldArr);
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $infoModel = new ExpenseInfo();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row = $row->toArray();
            $infos = $infoModel->getInfo($ids);
            $row['info'] = json_encode($infos);
            $table = $infoModel->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME as name,COLUMN_COMMENT as comment,DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            //排除字段
            $excludeFields = ['id','expense_id','admin_id','createtime','updatetime'];
            foreach ($list as $k => $v) {
                if (in_array($v['name'], $excludeFields)) {
                    continue;
                }
                $fieldArr[] = $v;
            }
            $this->view->assign('fields', $fieldArr);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $enableEdit = $this->auth->check('kuerp/expense/approvedEdit');
        if($row['check_status']==1 && !$enableEdit){
            $this->error('不能编辑审核中的数据');
        }
        if($row['check_status']==2 && !$enableEdit){
            $this->error('不能编辑已审核的数据');
        }
        if($row['pay_status']==1){
            $this->error('不能编辑已打款的数据');
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['id'] = $ids;
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->editExpense($params, $row);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function changePayStatus($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res =$this->model->where(['id'=>$ids])->update(['pay_status'=>1,'pay_time' => time(), 'pay_admin_id' => $this->auth->id,'updatetime'=>time()]);
        if($res){
            $this->success();
        }else{
            $this->error('打款失败');
        }
    }

    /**
     * 撤回申请
     */
    public function backApply($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $res = $this->model->where(['id'=>$ids])->update(['check_status'=>4,'check_step_sort'=>0,'check_uids'=>0,'check_time'=>0,'check_remark'=>'','updatetime'=>time()]);
        if($res){
            $this->success();
        }else{
            $this->error('撤回失败');
        }
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        if (empty($list)) {
            $this->error(__('No rows were found'));
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    public function detail($ids)
    {
        $row = $this->model->getInfo($ids);
        $row['admin'] = Admin::where('id', $row['admin_id'])->field('nickname,avatar')->find();
        $this->view->assign('row', $row);
        //获取审核信息
        // $logWhere = [
        //     'relation_type' => 'expense',
        //     'relation_id' => $ids,
        // ];
        // $logList = Db::name('examine_log')->where($logWhere)->order('id desc')->select();
        // if (!empty($logList)) {
        //     $admin_ids = array_column($logList,'admin_id');
        //     $admin_data = Db::name('admin')->where(['id'=>['in',$admin_ids]])->column('nickname,username,avatar','id');
        //     foreach ($logList as $log_k=>$log_v) {
        //         $logList[$log_k]['admin_name'] = $admin_data[$log_v['admin_id']]['nickname'] ?? $admin_data[$log_v['admin_id']]['username'] ?? '';
        //         $logList[$log_k]['admin_avatar'] = $admin_data[$log_v['admin_id']]['avatar'] ?? '';
        //         $logList[$log_k]['createtime'] = date('Y/m/d H:i', $log_v['createtime']);
        //     }
        // }

        // $this->assign('log_list',$logList);
        // $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
        $flows = Flows::getstepdetail(Flows::EXPENSE_STATUS, $ids);
        $this->assign('stepList',$flows['stepList']);

        $infoModel = new ExpenseInfo();
        

        $table = $infoModel->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME as name,COLUMN_COMMENT as comment,DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        //排除字段
        $excludeFields = ['id','expense_id','admin_id','createtime','updatetime'];
        foreach ($list as $k => $v) {
            if (in_array($v['name'], $excludeFields)) {
                continue;
            }
            $fieldArr[] = $v;
        }
        $this->view->assign('fields', $fieldArr);
        $infoList = $infoModel->getInfo($ids);
        if ($infoList) {
            //infoList最后加上各个字段合计值
            $sumRow = [];
            foreach ($fieldArr as $field) {
                if($field['type'] != 'varchar') {
                    $sumRow[$field['name']] = round(array_sum(array_column($infoList, $field['name'])),2);
                } else {
                    $sumRow[$field['name']] = $field['name'] == 'subject_matter' ? '合计' : '';
                }
            }
            $sumRow['expense_time_text'] = '';
            $infoList[] = $sumRow;
        }
        $this->assign('info_list',$infoList);
        $this->assign('ids',$ids);
        //标记通知已读
        Message::setRead(Message::EXPENSE_TYPE, $ids, $this->auth->id);
        return $this->view->fetch();
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $param = $this->request->param();
        if (isset($param['user_path'])) {
            if (file_exists($_SERVER['DOCUMENT_ROOT'].$param['user_path'])) {
                unlink($_SERVER['DOCUMENT_ROOT'].$param['user_path']); // 删除文件
            }
            exit();
        }
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall');
        $ruleWhere = [];
        if($isall != 3 && empty($ids)){
            $this->error(__('请选择要导出的数据'));
        }
        $ruleWhere['id'] = ['exp', DB::raw(' > 0 and ((check_status = 0 and admin_id = '.$this->auth->id.') or check_status > 0)')];
        //导出其中几条
        if (isset($ids) ) {
            $ruleWhere['id'] = array('in', $ids);
        }
        //导出全部
        if (isset($isall)) {
            if ($isall == 3) {
                $ruleWhere['id'] = ['exp', DB::raw(' > 0 and ((check_status = 0 and admin_id = '.$this->auth->id.') or check_status > 0)')];
            }
        }

        if (!$this->auth->isSuperAdmin()) {
            $adminids = $this->auth->adminids;
            //系统设置特定审核人员
            $config_site_examine_admins = config('site.examine_admins');
            if (!empty($config_site_examine_admins[$this->auth->id])) {
                $config_examine_admins = explode(',', $config_site_examine_admins[$this->auth->id]);
                $adminids = array_merge($adminids, $config_examine_admins);
            }
            $ruleWhere['admin_id'] = ['in', $adminids];
        }
        
        $filter = json_decode($this->request->get("filter", ''), true);
        $op = json_decode($this->request->get("op", '','trim'), true);
        if (isset($filter['income_month'])) {
            // 自定义处理
            $income_month = $filter['income_month'];
            // 处理完可以去掉也可以覆盖重构
            unset($filter['income_month'],$op['income_month']);
            $ruleWhere['income_month'] = strtotime($income_month);
        }
        $this->request->get(['filter'=>json_encode($filter,true)]);
        $this->request->get(['op'=>json_encode($op,true)]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->with(['expenseinfo'])
            ->where($where)
            ->where($ruleWhere)
            ->order($sort, $order)
            ->select();
        $list = collection($list)->toArray();
        if (!$list) {
            $this->error('无导出数据');
        }

        $title = [
            '报销编码',
            '报销人',
            '报销总金额',
            '入账月份',
            '开始日期',
            '结束日期',
            '打款状态',
            '最后审核人',
            '审核状态',
        ];
        $infoModel = new ExpenseInfo();
        $table = $infoModel->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $fieldList = db()->query("SELECT COLUMN_NAME as name,COLUMN_COMMENT as comment,DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        //排除字段
        $excludeFields = ['id','expense_id','admin_id','createtime','updatetime'];
        foreach ($fieldList as $k => $v) {
            if (in_array($v['name'], $excludeFields)) {
                continue;
            }
            $fieldArr[] = $v;
            $title[] = $v['comment'];
        }
        $adminList = Admin::column('nickname', 'id');
        $checkStatusList = $this->model->getCheckStatusList();
        foreach ($list as $k => $v) {
            $field1 = array(
                $v['expense_code'],
                $adminList[$v['admin_id']] ?? '',
                $v['cost'] ?? 0,
                date('Y-m',$v['income_month']),
                date('Y-m-d',$v['start_time']),
                date('Y-m-d',$v['end_time']),
                $v['pay_status'] == 1 ? '已打款' : '未打款',
                $adminList[$v['check_last_uid']] ?? '',
                $checkStatusList[$v['check_status']] ?? '',
            );
            
            foreach ($v['expenseinfo'] as $key => $info) {
                $field2 = [];
                foreach ($fieldArr as $fieldinfo) {
                    $field2[] = $fieldinfo['name'] == 'expense_time' ? date('Y-m-d', $info[$fieldinfo['name']]) : ($info[$fieldinfo['name']] ?? '');
                }
                if ($key > 0) {
                    $field1 = array_fill(0, count($field1), '');
                }
                $field = array_merge($field1, $field2);
                $data[] = $field;
            }
        }

        $file = export_excel($title, $data, '报销单');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }
}

